<template>
  <div class="search-phones">
    <!-- 搜索|新增 -->
    <div class="set-parameters">
      <el-input
        v-model="accountName"
        size="small"
        placeholder="请输入账号名称"
        clearable
        maxlength="30"
        show-word-limit
        style="width: 220px"
      ></el-input>
      <el-button type="primary" size="small" @click="queryData">查询</el-button>
      <el-button type="primary" size="small" @click="showDialog">添加</el-button>
    </div>

    <!-- 信息展示 -->
    <el-table :data="tableData" stripe style="width: 100%" height="60px">
      <el-table-column prop="account" label="账号" header-align="center" align="center"></el-table-column>
      <el-table-column prop="password" label="密码" header-align="center" align="center"></el-table-column>
      <el-table-column prop="nickname" label="昵称" header-align="center" align="center"></el-table-column>
      <el-table-column label="状态" header-align="center" align="center">
        <template slot-scope="scope">
          <span v-text="scope.row.state === 1 ? '正常' : '禁用'"></span>
        </template>
      </el-table-column>
      <el-table-column label="等级" prop="level" header-align="center" align="center"></el-table-column>
      <el-table-column label="创建时间" header-align="center" align="center">
        <template slot-scope="scope">
          <span v-text="$options.filters.transformTime2Minute(scope.row.createTime)"></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" header-align="center" align="center" width="160">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button
            size="mini"
            style="background-color: #ff9f00; color: #ffffff"
            type="warning"
            @click="handleDelete(scope.$index, scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      :current-page="pageNo"
      :page-sizes="[20, 40, 60, 80]"
      :page-size="pageSize"
      :pager-count="5"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>

    <el-dialog :modal="false" :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form ref="ruleForm" :model="form" :rules="rules">
        <el-form-item label="账号" :label-width="formLabelWidth" prop="account">
          <el-input
            v-model="form.account"
            placeholder="请输入账号名称"
            clearable
            maxlength="30"
            show-word-limit
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            clearable
            show-password
            maxlength="30"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" :label-width="formLabelWidth" prop="checkPassword">
          <el-input
            v-model="form.checkPassword"
            type="password"
            placeholder="请再次输入密码"
            clearable
            show-password
            maxlength="30"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="昵称" :label-width="formLabelWidth" prop="nickname">
          <el-input
            v-model="form.nickname"
            placeholder="请输入昵称"
            clearable
            maxlength="30"
            show-word-limit
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth" required prop="state">
          <el-switch v-model="form.state" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
        </el-form-item>
        <el-form-item label="账号等级" :label-width="formLabelWidth">
          <el-select v-model="form.level" placeholder="请选择" filterable clearable style="width: 100%">
            <el-option v-for="item in levels" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateOrAddAccount">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { queryAccounts, addAccount, deleteAccounts, updateAccount } from '@/api/httpApiAdmin'

export default {
  name: 'AccountManagement',
  data() {
    const validateName = (rule, value, callback) => {
      const reg = /^[\S\u4e00-\u9fa5a-z0-9_-]{1,16}$/
      if (reg.test(value)) {
        callback()
      } else {
        callback(new Error('账号必须由1-16个汉字、英文、数字、下划线、中划线组成'))
      }
    }
    const validatePass = (rule, value, callback) => {
      const reg = /^[0-9a-z]{6,16}$/gi
      if (reg.test(value)) {
        if (this.form.checkPassword !== '') {
          this.$refs.ruleForm.validateField('checkPassword')
        }
        callback()
      } else {
        callback(new Error('设备号长度6-16位,必须是数字或字母!'))
      }
    }
    const checkPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      tableData: [], // 表格中的数据
      accountName: '', // 账号名称
      pageNo: 1, // 第几页
      pageSize: 20, // 每页几个数据
      total: 0, // 总数
      dialogTitle: '添加账号',
      dialogVisible: false, // 显示dialog
      currentAccount: {}, // 要编辑的部门
      formLabelWidth: '120px',
      form: {
        account: '', // 账号名称
        password: '', //  密码
        checkPassword: '', // 确认密码
        nickname: '', // 昵称
        cid: '', // SupplierId （商户id）
        state: true, // 账号状态1正常2禁用
        level: 1 // 一般用不到，如果要权限管理自己实现
      }, // 表单
      rules: {
        account: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { validator: validateName, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: checkPass, trigger: 'blur' }
        ],
        nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }]
      }, // 表单验证
      levels: [
        {
          label: '一级',
          value: 1
        },
        {
          label: '二级',
          value: 2
        },
        {
          label: '三级',
          value: 3
        },
        {
          label: '四级',
          value: 4
        },
        {
          label: '五级',
          value: 5
        }
      ]
    }
  },
  computed: {
    ...mapState({
      adminInfo: 'adminInfo'
    })
  },
  watch: {
    accountName(val) {
      if (val.trim() === '') {
        this.queryData()
      }
    }
  },
  mounted() {
    this.queryDataSilence()
  },
  methods: {
    // 分页查询数据
    queryData() {
      queryAccounts(this.adminInfo.cid, this.accountName, this.pageNo, this.pageSize).then((res) => {
        if (res.code === 0) {
          this.tableData = res.data.rows || []
          this.total = res.data.records || 0
          this.$message({
            type: 'success',
            message: '查询成功！',
            duration: 1000
          })
        }
      })
    },
    queryDataSilence() {
      queryAccounts(this.adminInfo.cid, this.accountName, this.pageNo, this.pageSize).then((res) => {
        if (res.code === 0) {
          this.tableData = res.data.rows || []
          this.total = res.data.records || 0
        }
      })
    },
    // 修改pageSize
    handleSizeChange(val) {
      if (this.pageSize === val) return
      this.pageSize = val
      this.queryData()
    },
    // 修改当前页
    handleCurrentChange(val) {
      this.pageNo = val
      this.queryData()
    },
    // 显示dialog
    showDialog() {
      this.resetForm()
      this.dialogTitle = '添加账号'
      this.dialogVisible = true
    },
    // 修改或新建部门
    updateOrAddAccount() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const { id, account, password, nickname, state, level } = this.form
          const cid = this.adminInfo.cid
          if (this.dialogTitle === '添加账号') {
            addAccount(account, password, nickname, cid, state ? 1 : 2, level).then((res) => {
              if (res.code === 0) {
                this.queryDataSilence()
                this.dialogVisible = false
                this.$message({
                  type: 'success',
                  message: '添加账号成功!',
                  duration: 1000
                })
              }
            })
          } else {
            updateAccount(id, account, password, nickname, cid, state ? 1 : 2, level).then((res) => {
              if (res.code === 0) {
                this.dialogVisible = false
                this.queryDataSilence()
                this.$message({
                  type: 'success',
                  message: '更新成功',
                  duration: 1000
                })
              }
            })
          }
        } else {
          return false
        }
      })
    },
    // 重置表单
    resetForm() {
      this.form = {
        account: '', // 账号名称
        password: '', //  密码
        checkPassword: '', // 确认密码
        nickname: '', // 昵称
        cid: '', // SupplierId （商户id）
        state: true // 账号状态1正常2禁用
      }
    },
    // 显示编辑dialog
    handleEdit(index, row) {
      for (const key in row) {
        if (row.hasOwnProperty(key)) {
          if (key === 'state') {
            this.form[key] = row[key] === 1
          } else {
            this.form[key] = row[key]
          }
        }
      }
      this.currentAccount = row
      this.dialogTitle = '编辑账号'
      this.dialogVisible = true
    },
    // 删除
    handleDelete(index, row) {
      this.$confirm('是否删除客服账号！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteAccounts(row.id).then((res) => {
            if (res.code === 0) {
              const pn = Math.ceil((this.total - 1) / this.pageSize)
              if (this.pageNo > pn) {
                this.pageNo = pn
              }
              this.queryDataSilence()
              this.$message({
                type: 'success',
                message: '删除成功!',
                duration: 1000
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消',
            duration: 1000
          })
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.search-phones {
  height: 100%;
  display: flex;
  flex-direction: column;

  .set-parameters {
    padding: 10px 5px;
    display: flex;
    align-items: center;
    border-bottom: solid $border-color-1 2px;
    .el-button {
      margin-left: 20px;
    }
  }

  .el-pagination {
    padding: 5px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-top: solid 1px $border-color-1;
    background-color: white;
  }

  ::v-deep .el-dialog {
    width: 500px;
    .el-form {
      width: 400px;
    }
  }
}
</style>
